package megrez.bussiness.system.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import lombok.AllArgsConstructor;
import megrez.bussiness.system.entity.Dict;
import megrez.bussiness.system.entity.DictDetail;
import megrez.bussiness.system.repository.DictDetailRepository;
import megrez.bussiness.system.repository.DictRepository;
import megrez.bussiness.system.util.SystemErrorCode;
import megrez.bussiness.system.util.SystemException;
import megrez.common.util.EntityMissingException;

/**
 * 字典服务
 * 
 * @author Lucky Yang
 * @since 0.0.1
 */
@Service
@AllArgsConstructor
public class DictService {
    private final DictRepository dictRepository;
    private final DictDetailRepository dictDetailRepository;

    public Dict findByDictId(Long dictId) {
        return dictRepository.findById(dictId).orElseThrow(EntityMissingException::new);
    }

    public DictDetail findByDictDetailId(Long dictDetailId) {
        return dictDetailRepository.findById(dictDetailId).orElseThrow(EntityMissingException::new);
    }

    /**
     * 更新字典
     * 
     * @param dictId 字典
     * @param data   数据
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateDict(Long dictId, Dict data) {
        Dict entity = this.findByDictId(dictId);
        entity.copy(data);
        dictRepository.save(entity);
    }

    /**
     * 更新字典明细
     * 
     * @param dictDetailId 字典明细
     * @param data         数据
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateDictDetail(Long dictDetailId, DictDetail data) {
        DictDetail entity = this.findByDictDetailId(dictDetailId);
        entity.copy(data);
        dictDetailRepository.save(entity);
    }

    /**
     * 保存字典明细
     * 
     * @param dictId 字典
     * @param data   字典明细数据
     */
    @Transactional(rollbackFor = Exception.class)
    public DictDetail saveDictDetail(Long dictId, DictDetail data) {
        Dict dict = this.findByDictId(dictId);
        data.setDict(dict);
        return dictDetailRepository.save(data);
    }

    public void deleteDictById(Long dictId) {
        dictRepository.findById(dictId).ifPresent(dict -> {
            if (dictDetailRepository.countByDict(dict) > 0) {
                throw new SystemException(SystemErrorCode.DELETE_DICT_HAS_CHILD);
            }

            dictRepository.delete(dict);
        });
    }
}
